/*
 * Daniel R Padilla
 *
 * Copyright (c) 2007, Daniel R Padilla
 *
 * This copyrighted material is made available to anyone wishing to use, modify,
 * copy, or redistribute it subject to the terms and conditions of the GNU
 * Lesser General Public License, as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public License
 * for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this distribution; if not, write to:
 * Free Software Foundation, Inc.
 * 51 Franklin Street, Fifth Floor
 * Boston, MA  02110-1301  USA
 */
package org.databasefacade;


import java.lang.reflect.Method;
import java.sql.Connection;

import javax.sql.DataSource;

import org.databasefacade.exception.DatabaseFacadeException;


/**
 * The class is used to open the connection for the application. *  
 */
public class DatabaseConnectionManager {
   public ConnectionProperties connProps;
  

    public void init(ConnectionProperties props) {
        connProps = props;
    }
    private DataSource getDataSource() throws DatabaseFacadeException {
    	Object ds = null;
    	try {
    		// Get the vendor DataSource class
    		Class vendorDataSourceClass = Class.forName(connProps.getDataSourceClass());
    		
    		// Get the dynamic method calls that will be made
    		Class[] partypes = new Class[]{String.class};
     		
    		// Get an instance of the data source class
    		ds = vendorDataSourceClass.newInstance();
    		
    		for (int i=0; i < connProps.methodListSize(); i++) {
    			String methodName = connProps.getMethodName(i);
    			String param = connProps.getParameter(i);
    			Method method = vendorDataSourceClass.getMethod(methodName, partypes);
    			method.invoke(ds, param);
    		}

    	} catch (Exception e) {
        	LogManager.error("Unable to obtain datasource", e);
        	e.printStackTrace();
            throw new DatabaseFacadeException(e, "Could not establish datasource connection");
    	}
        return (DataSource) ds;
    }

    public Connection getConnection() throws DatabaseFacadeException {
        DataSource ds = getDataSource();
        try {
            Connection conn = ds.getConnection();
            conn.setAutoCommit(false);
            return conn;
        } catch (Exception e) {
        	LogManager.error("Unable to obtain connection", e);
            throw new DatabaseFacadeException(e, "Could not establish connection");
        }
    }
    
  

}
